from rest_framework.serializers import ModelSerializer  # 序列化器
from .models import *  # 导入所有的模型类
from django.contrib.auth.models import User  # auth自带的用户表
from rest_framework import serializers
from rest_framework.fields import SerializerMethodField  # 自定义数据格式模块

# 文章序列化器
class ArticleSerializer(ModelSerializer): # 序列化器类
    user_name = serializers.CharField(source='user.username',read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar',read_only=True)
    label_name = serializers.CharField(source='label.name',read_only=True)

    class Meta:
        model = Article  # 转序列化器
        exclude = ['is_delete']  # 不想展示的字段

# 子级评论序列化器 2
class SonCommentSerializer(ModelSerializer): # 序列化器类
    user_name = serializers.CharField(source='user.username',read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar',read_only=True)
    reply_username = SerializerMethodField()  # 回复评论的用户名

    class Meta:
        model = Comment  # 转序列化器
        exclude = ['is_delete']  # 不想展示的字段

    def get_reply_username(self,comment):
        return Comment.objects.get(id=comment.reply_comment).user.username

# 父级评论序列化器 1
class CommentSerializer(ModelSerializer): # 序列化器类
    user_name = serializers.CharField(source='user.username',read_only=True)
    user_avatar = serializers.CharField(source='user.userdetail.avatar',read_only=True)
    sonComment = SerializerMethodField()

    class Meta:
        model = Comment  # 转序列化器
        exclude = ['is_delete']  # 不想展示的字段

    def get_sonComment(self,comment):
        # 序列化嵌套
        serializer = SonCommentSerializer(Comment.objects.filter(parent_comment=comment.id),many=True)
        data = serializer.data
        data.reverse()  # 反向查询
        return data




